package com.zzb.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzb.base.utils.StringUtil;
import com.zzb.ucenter.feign.CheckCodeFeign;
import com.zzb.ucenter.mapper.XcCompanyUserMapper;
import com.zzb.ucenter.mapper.XcUserMapper;
import com.zzb.ucenter.model.dto.AuthParamsDto;
import com.zzb.ucenter.model.dto.XcUserExt;
import com.zzb.ucenter.model.po.XcCompanyUser;
import com.zzb.ucenter.model.po.XcUser;
import com.zzb.ucenter.service.AuthService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @Author zzb
 * @Date 2024/6/25 16:38
 * @Version 1.0
 * @description
 */
@Service("password_authservice")
public class PasswordAuthServiceImpl implements AuthService {
    @Resource
    private XcUserMapper xcUserMapper;
    @Resource
    private PasswordEncoder bCryptPasswordEncoder;
    @Resource
    private CheckCodeFeign checkCodeFeign;
    @Resource
    private RestTemplate restTemplate;
    @Autowired
    private XcCompanyUserMapper xcCompanyUserMapper;

    @Override
    public XcUserExt execute(AuthParamsDto authParamsDto) {
        //校验验证码
        String checkcode = authParamsDto.getCheckcode();
        String checkcodekey = authParamsDto.getCheckcodekey();
        //判断验证码是否为空
        if (StringUtil.isBlank(checkcode) || StringUtil.isBlank(checkcodekey)) {
            throw new RuntimeException("验证码为空");
        }
        Boolean isVerify = checkCodeFeign.verify(checkcodekey, checkcode);
        if (!isVerify) {
            throw new RuntimeException("验证码输入错误");
        }
        //获取用户名
        String username = authParamsDto.getUsername();
        //查询该用户是否存在
        XcUser xcUser = xcUserMapper
                .selectOne(new LambdaQueryWrapper<XcUser>().eq(XcUser::getUsername, username));
        //用户不存在
        if (xcUser == null) {
            throw new RuntimeException("该用户暂不存在");
        }
        //用户存在
        XcUserExt xcUserExt = new XcUserExt();
        BeanUtils.copyProperties(xcUser, xcUserExt);
        //查询是否关联机构
        XcCompanyUser xcCompanyUser = xcCompanyUserMapper.selectOne(new LambdaQueryWrapper<XcCompanyUser>().eq(XcCompanyUser::getUserId, xcUserExt.getId()));
        if (xcCompanyUser != null) {
            xcUserExt.setCompanyId(xcCompanyUser.getCompanyId());
        }
        //获取数据库密码
        String passwordDb = xcUser.getPassword();
        //获取用户输入密码
        String password = authParamsDto.getPassword();
        //比对密码
        boolean matches = bCryptPasswordEncoder.matches(password, passwordDb);
        //密码错误
        if (!matches) {
            throw new RuntimeException("用户密码输入有误");
        }
        //密码正确
        return xcUserExt;
    }
}
